import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，重定向到操作台
      next({ path: '/dashboard' })
      NProgress.done()
    } else if (to.path === '/') {
      // 如果访问根路径，直接跳转到dashboard
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      // 判断当前用户是否已拉取完user_info信息
      const hasGetUserInfo = store.getters.username
      if (hasGetUserInfo) {
        // 判断是否已生成路由
        const hasRoles = store.getters.addRoutes && store.getters.addRoutes.length > 0
        if (hasRoles) {
          next()
        } else {
          try {
            // 获取用户角色信息
            const userInfo = store.getters.userInfo
            const role = userInfo.role || 'student' // 默认为学生角色
            
            // 根据角色生成可访问的路由表
            const accessRoutes = await store.dispatch('permission/generateRoutes', role)
            
            // 动态添加可访问路由
            router.addRoutes(accessRoutes)
            
            // hack方法 确保addRoutes已完成
            next({ ...to, replace: true })
          } catch (error) {
            // 移除token并跳转登录页面重新登录
            await store.dispatch('user/resetToken')
            Message.error(error || '出现错误，请重新登录')
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          }
        }
      } else {
        try {
          // 获取用户信息
          const userInfo = await store.dispatch('user/getInfo')
          const role = userInfo.role || 'student' // 默认为学生角色
          
          // 根据角色生成可访问的路由表
          const accessRoutes = await store.dispatch('permission/generateRoutes', role)
          
          // 动态添加可访问路由
          router.addRoutes(accessRoutes)
          
          // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // 移除token并跳转登录页面重新登录
          await store.dispatch('user/resetToken')
          Message.error(error || '出现错误，请重新登录')
          next('/login?redirect=/dashboard')
          NProgress.done()
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${encodeURIComponent('/dashboard')}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
